package com.ly.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ly.common.core.bean.R;
import com.ly.common.core.bean.dto.CommonBatchUpdateDTO;
import com.ly.common.core.exception.ServiceException;
import com.ly.system.system.bean.entity.SysRole;
import com.ly.system.mapper.SysRoleMapper;
import com.ly.system.mapper.SysUserMapper;
import com.ly.system.service.ISysRoleService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;

/**
 * 角色-服务
 *
 * @author jeecg
 * @since 2018-12-19
 */
@Service
@RequiredArgsConstructor
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements ISysRoleService {

    private final SysRoleMapper sysRoleMapper;
    private final SysUserMapper sysUserMapper;

    @Override
    public R getId(String id) {
        SysRole entity = this.getById(id);
        if (entity == null) {
            return R.fail("未找到对应数据");
        }
        return R.ok(entity);
    }

    @Override
    public R getList(SysRole entity) {
        List<SysRole> list = this.list(
                new LambdaQueryWrapper<SysRole>()
                        .like(StrUtil.isNotBlank(entity.getRoleCode()), SysRole::getRoleCode, entity.getRoleCode())
                        .like(StrUtil.isNotBlank(entity.getRoleName()), SysRole::getRoleName, entity.getRoleName())
                        .in(CollUtil.isNotEmpty(entity.getCodes()), SysRole::getRoleCode, entity.getCodes())
                        .in(CollUtil.isNotEmpty(entity.getIds()), SysRole::getId, entity.getIds())
                        .orderByDesc(SysRole::getCreateTime)
        );
        return R.ok(list);
    }

    @Override
    public R getPage(SysRole entity, Page<SysRole> page) {
        IPage<SysRole> pageList = this.page(
                page,
                new LambdaQueryWrapper<SysRole>()
                        .like(StrUtil.isNotBlank(entity.getRoleCode()), SysRole::getRoleCode, entity.getRoleCode())
                        .like(StrUtil.isNotBlank(entity.getRoleName()), SysRole::getRoleName, entity.getRoleName())
                        .in(CollUtil.isNotEmpty(entity.getCodes()), SysRole::getRoleCode, entity.getCodes())
                        .in(CollUtil.isNotEmpty(entity.getIds()), SysRole::getId, entity.getIds())
                        .orderByDesc(SysRole::getCreateTime)
        );
        return R.ok(pageList);
    }

    @Override
    public R add(SysRole entity) {
        if (StrUtil.isEmpty(entity.getRoleCode())) {
            entity.setRoleCode(RandomUtil.randomString(10));
        }
        boolean flag = this.save(entity);
        return flag ? R.ok(true, "创建成功") : R.fail("创建失败");
    }

    @Override
    public R edit(SysRole entity) {
        boolean flag = this.updateById(entity);
        return flag ? R.ok(true, "修改成功") : R.fail("修改失败");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R delete(String id) {
        this.checkAdminRoleRejectDel(id);
        // 1.删除角色和用户关系
        sysRoleMapper.deleteRoleUserRelation(id);
        // 2.删除角色和权限关系
        sysRoleMapper.deleteRolePermissionRelation(id);
        boolean flag = this.removeById(id);
        return flag ? R.ok(true, "删除成功") : R.fail("删除失败");
    }

    @Override
    public R deleteBatch(String ids) {
        boolean flag = this.removeByIds(Arrays.asList(ids.split(",")));
        return flag ? R.ok(true, "批量删除成功") : R.fail("批量删除失败");
    }

    @Override
    public R updateBatch(CommonBatchUpdateDTO<SysRole> dto) {
        List<SysRole> datas = dto.getDatas();
        boolean flag = this.saveOrUpdateBatch(datas);
        return flag ? R.ok(true, "批量修改成功") : R.fail("批量修改失败");
    }

    @Override
    public SysRole getRoleNoTenant(String roleCode) {
        return sysRoleMapper.getRoleNoTenant(roleCode);
    }

    @Override
    public void checkAdminRoleRejectDel(String ids) {
        LambdaQueryWrapper<SysRole> query = new LambdaQueryWrapper<>();
        query.in(SysRole::getId, Arrays.asList(ids.split(",")));
        query.eq(SysRole::getRoleCode, "admin");
        Long adminRoleCount = sysRoleMapper.selectCount(query);
        if (adminRoleCount > 0) {
            throw new ServiceException("admin角色，不允许删除！");
        }
    }
}
